const Router = require('koa-router');
const router = new Router();
const tool = require('../tools/tool')
const {db, Op, QueryTypes} = require("../models/db");

// 用户保存
router.post('/user/save', async ctx => {
    let formData = ctx.request.body.formData
    if(formData.mobile) {
        let mobile = /^1[3-9][0-9]{9}$/.test(formData.mobile)
        if(!mobile) return ctx.err('手机号码不正确')
    }
    formData.tenantId = ctx.user.tenantId
    formData.pinYin = tool.py(formData.name)
    if(formData.id) {
        formData.utime = tool.getTime()
        formData.uby = ctx.user.id
        if(formData.cellToLogin) {
            // 检测 是否有相同的手机号用户名
            let c = await db.models['admin'].count({
                where: {
                    username: formData.mobile,
                    id: {
                        [Op.ne]: formData.id
                    }
                }
            })
            if(c > 0) {
                return ctx.err('已有相同的手机号做为登录账号')
            }
            let d = await db.models['admin'].count({
                where: {
                    mobile: formData.mobile,
                    id: {
                        [Op.ne]: formData.id
                    }
                }
            })
            if(d > 0) {
                return ctx.err('已有相同的手机号')
            }
        }
        if(formData.username) {
            let uname = tool.xe.trim(formData.username)
            let c = await db.models['admin'].count({
                where: {
                    username: uname,
                    id: {
                        [Op.ne]: formData.id
                    }
                }
            })
            if(c > 0) {
                return ctx.err('已有相同的用户名')
            }
        }
        await db.models['admin'].update(formData, {
            where: {
                id: formData.id
            }
        })
    }
    else {
        formData.userpwd = tool.crypto.MD5('121121')
        formData.token = tool.uuid()
        formData.selfData = 1
        formData.allData = 0
        formData.ctime = tool.getTime()
        formData.cby = ctx.user.id
        formData.utime = tool.getTime()
        formData.uby = ctx.user.id
        if(formData.cellToLogin) {
            // 检测 是否有相同的手机号用户名
            let c = await db.models['admin'].count({
                where: {
                    username: mobile
                }
            })
            if(c > 0) {
                return ctx.err('已有相同的手机号做为登录账号')
            }
            if(c > 0) {
                return ctx.err('已有相同的手机号做为登录账号')
            }
            let d = await db.models['admin'].count({
                where: {
                    mobile: formData.mobile,
                }
            })
            if(d > 0) {
                return ctx.err('已有相同的手机号')
            }
        }
        if(formData.username) {
            let uname = tool.xe.trim(formData.username)
            let c = await db.models['admin'].count({
                where: {
                    username: uname
                }
            })
            if(c > 0) {
                return ctx.err('已有相同的用户名')
            }
        }
        await db.models['admin'].create(formData)
    }
    return ctx.suc('更新成功')
})
router.post('/user/altPwd', async ctx => {
    let id = ctx.request.body.id
    let userpwd = ctx.request.body.userpwd
    if(id && userpwd) {
        await db.models['admin'].update({
            userpwd: userpwd,
            token: tool.uuid(),
            uby: ctx.user.id,
            errCount: 0,
            utime: tool.getTime()
        }, {
            where: {
                id: id
            }
        })
        return  ctx.suc('已更新密码')
    }
    else {
        return ctx.err('请输入密码')
    }
})
// 设置数据权限
router.post('/user/dataAuth', async ctx => {
    let allData = ctx.request.body.allData
    let selfData = ctx.request.body.selfData
    let userId = ctx.request.body.userId
    let tid = ctx.user.tenantId;
    let owner = ctx.request.body.owner
    let dept = ctx.request.body.dept
    if(!userId) return ctx.err('未发现用户')
    await db.transaction(async t => {
        await db.models['admin'].update({
            allData: allData?1:0,
            selfData: selfData?1:0
        }, {
            where: {
                id: userId
            }
        }, {transaction: t})
        await db.models['adminDataOwer'].destroy({
            where: {
                selfId: userId
            }
        }, {transaction: t})
        await db.models['adminDataDept'].destroy({
            where: {
                selfId: userId
            }
        }, {transaction: t})
        if(owner.length > 0) {
            let ow = []
            owner.map(row => {
                ow.push({selfId: userId, owerId: row.id, tenantId: tid})
            })
            await db.models['adminDataOwer'].bulkCreate(ow, {transaction: t})
        }
        if(dept.length > 0) {
            let dp = []
            for (let i = 0; i < dept.length; i++) {
                dp.push({selfId: userId, deptId: dept[i], tenantId: tid})
            }
            await db.models['adminDataDept'].bulkCreate(dp, {transaction: t})
        }
    })
    return ctx.suc('更新成功')
})
// 删除用户
router.post('/user/del', async ctx => {
    let ids = ctx.request.body.ids
    let t = tool.getTime()
    // 先检测是否有客户。有客户先去转移
    let hasc = await db.models['contact'].count({
        where: {
            tenantId: ctx.user.tenantId,
            salesId: ids[0]
        }
    })
    if(hasc > 0) {
        return  ctx.err('该用户有 ' + hasc +' 个客户,请先转移后再删除')
    }
    await db.models['admin'].update({
        userpwd: null,
        token: tool.uuid(),
        uby: ctx.user.id,
        utime: t,
        isDel: 1,
        dby: ctx.user.id,
        dtime: t,
    }, {
        where: {
            id: ids[0]
        }
    })
    return  ctx.suc('已删除')
})
// 获取数据权限
router.post('/user/getDataAuth', async ctx => {
    let userId = ctx.request.body.userId
    let tid = ctx.user.tenantId
    let sql = `select id,name from admin where tenantId=${tid} and isDel=0 `
    let admins = await db.query(sql, {type: QueryTypes.SELECT})
    let hasAuth = await db.query(`select * from admin_data_ower where selfId=${userId} `, {type: QueryTypes.SELECT})
    let authIds = []
    hasAuth.map(row => {
        authIds.push(row.owerId)
    })
    let userList = []
    admins.map(row => {
        let obj = {checked: false, id: row.id, name: row.name}
        if(authIds.indexOf(row.id) !== -1) {
            obj.checked = true
        }
        userList.push(obj)
    })
    let sqld = `select id,name, pid from dept where tenantId=${tid} `
    let depts = await db.query(sqld, {type: QueryTypes.SELECT})
    let deptsAuth = await db.query(`select * from admin_data_dept where selfId=${userId}`, {type: QueryTypes.SELECT})
    let deptList = []
    let deptIds = []
    deptsAuth.map(row => {
        deptIds.push(row.deptId)
    })
    depts.map(row => {
        let obj = {
            id: row.id,
            name: row.name,
            pid: row.pid,
            checked: false
        }
        if(deptIds.indexOf(row.id) !== -1) {
            obj.checked = true
        }
        deptList.push(obj)
    })
    let allData = await db.models['admin'].findOne({
        where: {
            id: userId
        }
    })
    return ctx.suc('', {userList, deptList, allData: allData.allData === 1, selfData: allData.selfData === 1})
})
// 取当前用户的菜单列表
router.post('/user/getMenuList', async ctx => {
    // 从租户的菜单中取
    try {
        let roleId = ctx.user.roleId
        let tid = ctx.user.tenantId
        let role = await db.models['role'].findOne({
            where: {
                id: roleId
            }
        })

        let attr = ` id,name,pid,sort,routeId,icon,sep,allowAdd,allowEdit,allowDel,isBill,isReport,isAdmin,display, 1 canAdd,1 canEdit,1 canDel,1 canAccount,1 canWaste,bt,params,page, isMobile,isPc ,path ,type,tag,addRoute  `
        let hideMenu = ` select ${attr} from menu where id=1896 union all select ${attr} from menu where pid=1896 `
        let hideList = await db.query(hideMenu, {type: QueryTypes.SELECT})

        let allMenu = ` select b.* from tenant_menu a inner join menu b on a.menuId=b.id and a.tenantId=${tid} ` // 该租户有的菜单
        let sql = `select  a.id,a.name,a.pid,a.sort,a.routeId,a.icon,a.sep,a.allowAdd,a.allowEdit,a.allowDel,bt ,a.isBill,a.isReport,a.isAdmin,b.canAdd,
        b.canEdit,b.canDel,b.canAccount,b.canWaste,params,page ,a.isMobile,a.isPc, a.path ,a.type ,a.display ,a.tag,a.addRoute 
           from (${allMenu}) a inner join (select * from role_menu where roleId=${roleId}) b  
           on a.id=b.menuId where a.isDelete=0 and a.isAdmin=0 order by a.pid asc,a.sort asc,a.id asc `

        if(ctx.user.username === 'admin') {
            let str = `select id,name,pid,sort,routeId,icon,sep,allowAdd,allowEdit,allowDel,isBill,isReport,isAdmin,display,
            1 canAdd,1 canEdit,1 canDel,1 canAccount,1 canWaste,bt,params,page, isMobile,isPc ,path ,type,tag,addRoute from menu order by pid asc, sort asc,id asc `
            let list = await db.query(str, {type:　QueryTypes.SELECT})
            return ctx.suc('', list)
        }
        else if(role && role.name === '管理员') {
            let sqlstr = `select  id,name,pid,sort,routeId,icon,sep,allowAdd,allowEdit,allowDel,isBill,isReport,isAdmin,bt ,1 canAdd,display,
            1 canEdit,1 canDel,1 canAccount,1 canWaste,params,page, isMobile,isPc ,path ,type,tag,addRoute  from (${allMenu}) a where a.isAdmin=0 order by pid asc,sort asc,id asc `
            let list = await db.query(sqlstr, {type: QueryTypes.SELECT})
            list.map(row => {
                hideList.push(row)
            })
            return ctx.suc('', hideList)
        }
        let alist = await db.query(sql, {type: QueryTypes.SELECT})
        alist.map(row => {
            hideList.push(row)
        })

        return ctx.suc('', hideList)
    }
    catch (e) {
        console.log('菜单取回失败',e)
        return ctx.err('菜单取回失败')
    }
})
// 手机菜单列表
router.post('/user/getMenuListV4', async ctx => {
    let list = [
        {id: 1, pid: 0,title: '客户拜访',routeName: 'bf',path: 'bf',component: 'bf/bf',pageName:'',tag:'',addRoute: '',},
        {id: 2, pid: 0,title: '拜访记录',routeName: 'bfMy',path: 'bfMy',component: 'bf/bfMy',pageName:'',tag:'',addRoute: '',},
        {id: 3, pid: 0,title: '拜访轨迹',routeName: 'bfGj',path: 'bfGj',component: 'bf/bfGj',pageName:'',tag:'',addRoute: '',},
        {id: 4, pid: 0,title: '新增客户',routeName: 'contactAdd',path: 'contactAdd',component: 'contact/contactAdd',pageName:'',tag:'',addRoute: '',},
        {id: 5, pid: 0,title: '我的客户',routeName: 'contactMy',path: 'contactMy',component: 'contact/contactMy',pageName:'',tag:'',addRoute: '',},
        {id: 6, pid: 0,title: '拜访首页',routeName: 'bfHome',path: 'contactMy',component: 'contact/contactMy',pageName:'',tag:'',addRoute: '',},
        {id: 7, pid: 0,title: '新增收款',routeName: 'addSk',path: 'addSk',component: 'sk/addSk',pageName:'',tag:'',addRoute: '',},
        {id: 8, pid: 0,title: '交款核对',routeName: 'jkhd',path: 'jkhd',component: 'sk/jkhd',pageName:'',tag:'',addRoute: '',},
        {id: 9, pid: 0,title: '收款记录',routeName: 'skJl',path: 'skJl',component: 'sk/skJl',pageName:'',tag:'',addRoute: '',},
        {id: 10, pid: 0,title: '收款统计',routeName: 'skTj',path: 'skTj',component: 'sk/skTj',pageName:'',tag:'',addRoute: '',},
        {id: 11, pid: 0,title: '票据筛选',routeName: 'billFind',path: 'billFind',component: 'sk/billFind',pageName:'',tag:'',addRoute: '',},
    ]
    return ctx.suc('', list)
    // arr.push({
    //     id: row.id,
    //     pid: row.pid,
    //     tag: row.tag,
    //     addRoute: row.addRoute,
    //     name: row.routeName,
    //     path: '/'+row.path,
    //     component: row.component,
    //     meta: {
    //         title: row.name,
    //         icon: row.icon,
    //         type: row.type,
    //         hidden: !row.display,
    //         routeName: row.routeName,
    //         pageName: row.pageName
    //     }
    // })
})
router.post('/user/getAllMenu', async ctx => {
    // 从租户的菜单中取
    try {
        let list = await db.models['menu'].findAll()
        return ctx.suc('', list)
    }
    catch (e) {
        console.log('菜单取回失败',e)
        return ctx.err('菜单取回失败')
    }
})
router.post('/user/getUserById', async ctx => {
    let id = ctx.request.body.id
    let user = await db.models['admin'].findOne({
        where: {id: id}
    })
    let avatar = null
    if(user.avatar) {
        avatar = {
            fileName: user.avatar,
            url: tool.getPicUrl(user.avatar).url
        }
    }
    return ctx.suc('', {user, avatar})
})
// 恢复删除
router.post('/user/recover', async ctx => {
    let id = ctx.request.body.id
    let t = tool.getTime()
    // 先检测是否有客户。有客户先去转移
    let user = await db.models['admin'].findOne({
        where: {
            tenantId: ctx.user.tenantId,
            id: id
        }
    })
    if(!user) return ctx.err('未发现用户,可能已被彻底删除')
    user.isDel = 0
    user.dby = null
    user.dtime = null
    user.uby = ctx.user.id
    user.dtime = tool.getTime()
    await user.save()
    return  ctx.suc('用户已恢复，要登录还需设置密码')
})
router.post('/user/saveAvatar', async ctx => {
    let fileName = ctx.request.body.fileName
    let id = ctx.request.body.id
    db.models['admin'].update({
        avatar: fileName
    }, {
        where: {
            id: id
        }
    })
    return ctx.suc('图片上传成功')
})
// 用户管理
router.post('/user/userList', async ctx => {
    let tid = ctx.user.tenantId
    let sql = `select a.id,a.username,a.name,a.mobile,b.id deptId,b.name deptName,a.isDel,
       c.id roleId,c.name roleName,a.selfData,a.allData,a.cellToLogin from admin a left join dept b on a.deptId=b.id left join role c on a.roleId=c.id 
       where a.tenantId=${tid} `

    let ret = await tool.page(ctx, sql)

    return ret
})
// 更新线路的客户数
router.post('/user/setTers', async ctx => {
    let areaId = ctx.request.body.id;
    let model = await db.models['area'].findOne({
        where: {
            id: areaId
        }
    })
    if(model) {
        let c = await db.models['contact'].count({
            where: {
                areaId: areaId
            }
        })
        model.ters = c
        await model.save()
    }
    ctx.suc('')
})
// 扫码登录
router.post('/user/setScanLogin', async ctx => {
    let code = ctx.request.body.code
    if(code) {
        let scan = await db.models['loginScan'].findOne({
            where: {
                scanCode: code
            }
        })
        if (!scan) {
            const mode = await db.models['loginScan'].create({
                scanCode: code,
                userToken: ctx.user.token,
                confirm: 0,
                ctime: tool.getTime()
            })
            return ctx.suc('', mode)
        }
        else {
            scan.userToken = ctx.user.token
            await scan.save()
            return ctx.suc('', scan)
        }
    }
    else {
        return ctx.err('扫码登录失败')
    }
})
// 登录页面自动登录
router.post('/user/scanLogined', async ctx => {
    let code = ctx.request.body.code
    let model = await db.models['loginScan'].findOne({
        where: {
            scanCode: code
        }
    })
    if (model) {
        if(model.confirm === 0) {
            model.confirm = 1
            await model.save()
            let user = await db.models['admin'].findOne({
                where: {
                    token: model.userToken
                }
            })
            if (user) {
                return login(user.username, user.userpwd, ctx)
            }
            return ctx.suc('')
        }
        else {
            return ctx.err('二维码过期')
        }
        return ctx.err('')
    }
    return ctx.err('')
})
router.post('/user/login', async ctx => {
    let username = ctx.request.body.username;
    let userpwd = ctx.request.body.userpwd;
    if (!username) return ctx.err('请输入用户名');
    if (!userpwd) return ctx.err('请输入密码');
    username = username.trim();
    userpwd = userpwd.trim();
    let usr = await db.models['admin'].findOne({
        where: {
            username
        }
    })
    if(!usr) return ctx.err('没有此用户')
    if(usr.tenantId === 8) {
       // return ctx.err('请使用新版本 https://v5.sanzhiyun.cn')
    }
    return await tool.login(username, userpwd, ctx)
})


module.exports = router;